namespace Roids.SL.Framework
{
    using System.Collections.Generic;
    using Microsoft.Xna.Framework;
    using Microsoft.Xna.Framework.Graphics;

    public abstract class ParticleEmitter : SceneItem
    {
        private readonly IList<Particle> _dead = new List<Particle>();
        private readonly List<Particle> _particles = new List<Particle>();

        protected ParticleEmitter(Game game) : base(game)
        {
        }

        protected void AddParticle(Particle particle)
        {
            _particles.Add(particle);
        }

        public override void Update(GameTime gameTime)
        {
            var elapsed = gameTime.ElapsedGameTime.Seconds;

            foreach (var particle in _particles)
            {
                particle.X += particle.Velocity.X*elapsed;
                particle.Y += particle.Velocity.Y*elapsed;
                particle.Life -= particle.DecayRate*elapsed;

                if (particle.Life < 0) _dead.Add(particle);
            }

            foreach (var particle in _dead)
            {
                _particles.Remove(particle);
            }

            base.Update(gameTime);

            if (_particles.Count == 0) ReadyToRemove = true;
        }

        protected abstract void DrawParticle(GameTime gameTime, SpriteBatch spriteBatch, Particle particle);

        public override void Draw(GameTime gameTime, SpriteBatch batch)
        {
            foreach (var particle in _particles)
            {
                DrawParticle(gameTime, batch, particle);
            }

            base.Draw(gameTime, batch);
        }
    }
}